

import React, { useState, useEffect } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { authApi } from '../../api/auth';
import styles from './styles.module.css';

interface FormData {
  phone: string;
  password: string;
  confirmPassword: string;
}

interface FormErrors {
  phone: string;
  password: string;
  confirmPassword: string;
}

const RegisterPage: React.FC = () => {
  const navigate = useNavigate();
  
  // 表单数据状态
  const [formData, setFormData] = useState<FormData>({
    phone: '',
    password: '',
    confirmPassword: ''
  });
  
  // 表单错误状态
  const [formErrors, setFormErrors] = useState<FormErrors>({
    phone: '',
    password: '',
    confirmPassword: ''
  });
  
  // 密码显示状态
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  
  // 提交状态
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState<string>('');

  // 设置页面标题
  useEffect(() => {
    const originalTitle = document.title;
    document.title = '注册 - 学途';
    return () => {
      document.title = originalTitle;
    };
  }, []);

  // 表单验证函数
  const validatePhone = (phone: string): boolean => {
    const phoneRegex = /^1[3-9]\d{9}$/;
    return phoneRegex.test(phone);
  };

  const validatePassword = (password: string): boolean => {
    return password.length >= 6;
  };

  // 显示错误信息
  const showError = (field: keyof FormErrors, message: string) => {
    setFormErrors(prev => ({
      ...prev,
      [field]: message
    }));
  };

  // 隐藏错误信息
  const hideError = (field: keyof FormErrors) => {
    setFormErrors(prev => ({
      ...prev,
      [field]: ''
    }));
  };

  // 处理输入变化
  const handleInputChange = (field: keyof FormData, value: string) => {
    setFormData(prev => ({
      ...prev,
      [field]: value
    }));
  };

  // 处理输入框失去焦点验证
  const handleInputBlur = (field: keyof FormData) => {
    const value = formData[field];
    
    if (field === 'phone' && value) {
      if (!validatePhone(value)) {
        showError('phone', '请输入有效的手机号码');
      } else {
        hideError('phone');
      }
    }
    
    if (field === 'password' && value) {
      if (!validatePassword(value)) {
        showError('password', '密码长度至少6位');
      } else {
        hideError('password');
      }
    }
    
    if (field === 'confirmPassword' && value) {
      if (value !== formData.password) {
        showError('confirmPassword', '两次输入的密码不一致');
      } else {
        hideError('confirmPassword');
      }
    }
  };

  // 切换密码显示状态
  const togglePasswordVisibility = (field: 'password' | 'confirmPassword') => {
    if (field === 'password') {
      setShowPassword(!showPassword);
    } else {
      setShowConfirmPassword(!showConfirmPassword);
    }
  };

  // 处理表单提交
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    // 清除所有错误信息
    setFormErrors({
      phone: '',
      password: '',
      confirmPassword: ''
    });
    setSubmitError('');

    // 获取表单数据
    const { phone, password, confirmPassword } = formData;

    // 验证表单
    let hasError = false;

    if (!phone.trim()) {
      showError('phone', '请输入手机号码');
      hasError = true;
    } else if (!validatePhone(phone.trim())) {
      showError('phone', '请输入有效的手机号码');
      hasError = true;
    }

    if (!password) {
      showError('password', '请输入密码');
      hasError = true;
    } else if (!validatePassword(password)) {
      showError('password', '密码长度至少6位');
      hasError = true;
    }

    if (!confirmPassword) {
      showError('confirmPassword', '请确认密码');
      hasError = true;
    } else if (password !== confirmPassword) {
      showError('confirmPassword', '两次输入的密码不一致');
      hasError = true;
    }

    if (hasError) return;

    // 显示加载状态并调用后端注册接口
    setIsSubmitting(true);
    try {
      const payload = {
        username: phone.trim(),
        password,
        enable: true,
        profile: {
          nickName: '',
          gender: 0,
          avatar: '',
          address: '',
          email: '',
          idCard: '',
          eduDegree: '',
          graduateSchool: '',
          specialty: '',
          rank: '',
          subject: '',
          phone: phone.trim(),
        },
        roleIds: [8],
      };

      await authApi.register(payload);
      // 注册成功，跳转到登录页
      navigate('/login');
    } catch (error: any) {
      setSubmitError(error?.message || '注册失败，请稍后重试');
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className={styles.pageWrapper}>
      {/* 顶部导航栏 */}
      <header className="bg-white shadow-sm border-b border-border-light fixed top-0 left-0 right-0 z-50">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between items-center h-16">
            {/* Logo和网站名称 */}
            <div className="flex items-center space-x-3">
              <div className="w-8 h-8 bg-primary rounded-lg flex items-center justify-center">
                <i className="fas fa-graduation-cap text-white text-lg"></i>
              </div>
              <span className="text-xl font-bold text-text-primary">学途</span>
            </div>
            
            {/* 主导航菜单 */}
            <nav className="hidden md:flex items-center space-x-8">
              <Link to="/home" className="text-text-secondary hover:text-primary py-1 transition-colors">首页</Link>
              <Link to="/course-list" className="text-text-secondary hover:text-primary py-1 transition-colors">课程中心</Link>
              <Link to="/about-us" className="text-text-secondary hover:text-primary py-1 transition-colors">关于我们</Link>
              <Link to="/help-center" className="text-text-secondary hover:text-primary py-1 transition-colors">帮助中心</Link>
            </nav>
            
            {/* 搜索框 */}
            <div className="hidden lg:flex items-center">
              <div className="relative">
                <input 
                  type="text" 
                  placeholder="搜索课程、讲师..." 
                  className="w-64 pl-10 pr-4 py-2 border border-border-light rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
                />
                <i className="fas fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-text-secondary"></i>
              </div>
            </div>
            
            {/* 用户菜单 */}
            <div className="flex items-center space-x-4">
              <button className="relative p-2 text-text-secondary hover:text-primary transition-colors">
                <i className="fas fa-bell text-lg"></i>
                <span className="absolute -top-1 -right-1 w-3 h-3 bg-danger rounded-full"></span>
              </button>
              
              {/* 未登录状态 */}
              <div className="flex items-center space-x-3">
                <Link to="/login" className="px-4 py-2 text-text-secondary hover:text-primary transition-colors">登录</Link>
                <Link to="/register" className="px-4 py-2 bg-primary text-white rounded-lg hover:bg-blue-600 transition-colors">注册</Link>
              </div>
            </div>
          </div>
        </div>
      </header>

      {/* 主内容区域 */}
      <main className="pt-16 min-h-screen flex items-center justify-center py-12">
        <div className="w-full max-w-md mx-auto px-4 sm:px-6 lg:px-8">
          {/* 注册表单卡片 */}
          <div className={`${styles.registerCard} p-8`}>
            {/* 注册标题 */}
            <div className="text-center mb-8">
              <div className="w-16 h-16 bg-primary rounded-full flex items-center justify-center mx-auto mb-4">
                <i className="fas fa-user-plus text-white text-2xl"></i>
              </div>
              <h1 className="text-2xl font-bold text-text-primary mb-2">注册学途账户</h1>
              <p className="text-text-secondary">加入我们，开启您的学习之旅</p>
            </div>

            {/* 注册表单 */}
            <form onSubmit={handleSubmit} className="space-y-6">
              {/* 手机号输入框 */}
              <div className="space-y-2">
                <label htmlFor="phone" className="block text-sm font-medium text-text-primary">手机号码 *</label>
                <input 
                  type="tel" 
                  id="phone" 
                  name="phone" 
                  value={formData.phone}
                  onChange={(e) => handleInputChange('phone', e.target.value)}
                  onBlur={() => handleInputBlur('phone')}
                  className={`w-full px-4 py-3 border border-border-light rounded-lg ${styles.formInputFocus}`}
                  placeholder="请输入您的手机号码" 
                  required 
                />
                {formErrors.phone && (
                  <div className={styles.errorMessage}>{formErrors.phone}</div>
                )}
              </div>

              {/* 密码输入框 */}
              <div className="space-y-2">
                <label htmlFor="password" className="block text-sm font-medium text-text-primary">密码 *</label>
                <div className="relative">
                  <input 
                    type={showPassword ? 'text' : 'password'} 
                    id="password" 
                    name="password" 
                    value={formData.password}
                    onChange={(e) => handleInputChange('password', e.target.value)}
                    onBlur={() => handleInputBlur('password')}
                    className={`w-full px-4 py-3 pr-12 border border-border-light rounded-lg ${styles.formInputFocus}`}
                    placeholder="请设置您的密码（至少6位）" 
                    required 
                  />
                  <button 
                    type="button" 
                    onClick={() => togglePasswordVisibility('password')}
                    className="absolute right-4 top-1/2 transform -translate-y-1/2 text-text-secondary hover:text-text-primary"
                  >
                    <i className={`fas ${showPassword ? 'fa-eye-slash' : 'fa-eye'}`}></i>
                  </button>
                </div>
                {formErrors.password && (
                  <div className={styles.errorMessage}>{formErrors.password}</div>
                )}
                <div className="text-xs text-text-secondary">密码应包含字母和数字，长度至少6位</div>
              </div>

              {/* 确认密码输入框 */}
              <div className="space-y-2">
                <label htmlFor="confirm-password" className="block text-sm font-medium text-text-primary">确认密码 *</label>
                <div className="relative">
                  <input 
                    type={showConfirmPassword ? 'text' : 'password'} 
                    id="confirm-password" 
                    name="confirm-password" 
                    value={formData.confirmPassword}
                    onChange={(e) => handleInputChange('confirmPassword', e.target.value)}
                    onBlur={() => handleInputBlur('confirmPassword')}
                    className={`w-full px-4 py-3 pr-12 border border-border-light rounded-lg ${styles.formInputFocus}`}
                    placeholder="请再次输入密码" 
                    required 
                  />
                  <button 
                    type="button" 
                    onClick={() => togglePasswordVisibility('confirmPassword')}
                    className="absolute right-4 top-1/2 transform -translate-y-1/2 text-text-secondary hover:text-text-primary"
                  >
                    <i className={`fas ${showConfirmPassword ? 'fa-eye-slash' : 'fa-eye'}`}></i>
                  </button>
                </div>
                {formErrors.confirmPassword && (
                  <div className={styles.errorMessage}>{formErrors.confirmPassword}</div>
                )}
              </div>

              {/* 注册按钮 */}
              <button 
                type="submit" 
                disabled={isSubmitting}
                className={`${styles.registerButton} w-full py-3 font-medium`}
              >
                <span>{isSubmitting ? '注册中...' : '立即注册'}</span>
                {isSubmitting && (
                  <i className="fas fa-spinner fa-spin ml-2"></i>
                )}
              </button>

              {/* 提交错误信息 */}
              {submitError && (
                <div className={styles.errorMessage}>{submitError}</div>
              )}

              {/* 已有账户登录链接 */}
              <div className="text-center">
                <p className="text-text-secondary">
                  已有账户？
                  <Link to="/login" className="text-primary hover:text-blue-600 font-medium transition-colors ml-1">
                    立即登录
                  </Link>
                </p>
              </div>
            </form>
          </div>

          {/* 底部链接 */}
          <div className="mt-8 text-center space-y-4">
            <div className="flex justify-center space-x-6 text-sm text-text-secondary">
              <Link to="/privacy-policy" className="hover:text-primary transition-colors">隐私政策</Link>
              <Link to="/terms-of-service" className="hover:text-primary transition-colors">服务条款</Link>
              <Link to="/help-center" className="hover:text-primary transition-colors">帮助中心</Link>
            </div>
            <p className="text-xs text-text-secondary">
              © 2024 学途. 保留所有权利.
            </p>
          </div>
        </div>
      </main>
    </div>
  );
};

export default RegisterPage;

